/**
 * 涵盖基本信息的表单项
 */
import CascaderProject from "@rc/pages/components/async/cascader-project.vue";
import SelectSubject from "@rc/pages/components/async/select-subject.vue";
import CascaderChapter from "@rc/pages/components/async/cascader-chapter.vue";
import SelectTeacher from "@rc/pages/components/async/select-teacher.vue";
import KnowledgeDialog from "@rc/pages/components/knowledge-dialog/index.vue";
import KnowledgeDeleteDialog from "@rc/pages/components/knowledge-delete-dialog/index.vue";
export default {
	props: {
		max: {
			/**控制修改max的值控制展开和收起隐藏*/
			type: Number,
			default: 6
		},
		basicInfo: {
			/* 表单回显的数据 */
			type: Object,
			default: () => {}
		},
		/**
		 * 组件内改动需要立即向外同步数据时，设置此值为true,否则不传
		 */
		isSync: {
			type: Boolean,
			default: false
		},
		propList: {
			/*要显示的表单项，默认显示全部 */
			type: Array,
			default: () => ["projectId", "subjectId", "chapter", "knowledgePoint", "questionType", "questionDeveloperId"]
		},
		rulesPropList: {
			/*要校验的表单项prop propList中传递对应prop值时有效*/
			type: Array,
			default: () => []
		},
		disablePropList: {
			/*禁用的表单项key  propList中存在chapter有效*/
			type: Array,
			default: () => []
		},
		chapterMultiple: {
			/* 章节表单项是否多选 默认单选 propList中存在chapter有效*/
			type: Boolean,
			default: false
		},
		teacherAvlstatus: {
			/* 研发人- 教师状态Y:可用;N:不可用 propList中存在questionDeveloperId时有效*/
			type: String,
			default: ""
		},
        showDisabledProject:{
            /* 是否显示禁用的项目-true:显示;false:不显示*/
			type: Boolean,
			default: false
        },
        showDisabledSubject:{
            /* 是否显示禁用的科目-true:显示;false:不显示*/
			type: Boolean,
			default: false
        },
        showDisabledChapter:{
            /* 是否显示禁用的章节-true:显示;false:不显示*/
			type: Boolean,
			default: false
        },
        knowledgeMultiple:{/* 知识点是否多选 propList中存在knowledgePointId时有效*/
            type: Boolean,
            default: false
        },
		inline: {
			/*同element-ui form表单 inline */
			type: Boolean,
			default: true
		},
		labelWidth: {
			/* 同element-ui form表单 labelWidth */
			type: String,
			default: ""
		},
		labelPosition: {
			/* 同element-ui form表单 labelPosition */
			type: String,
			default: ""
		},
		labelSuffix: {
			/* 同element-ui form表单 labelSuffix */
			type: String,
			default: ""
		}
	},
	components: {
		CascaderProject,
		SelectSubject,
		CascaderChapter,
		SelectTeacher,
		KnowledgeDialog,
        KnowledgeDeleteDialog
	},
	watch: {
		basicInfo: {
			deep: true,
			immediate: true,
			handler(basicInfo) {
				/* 初始化表单数据 */
				if (basicInfo) {
                    this.basicForm = {
                        ...this.basicForm,
                        ...JSON.parse(JSON.stringify(basicInfo))
                    };
                    this.$nextTick(() => {
                        this.$refs.basicForm.clearValidate();
                    });
				}
			}
		},
		basicForm: {
			deep: true,
			immediate: true,
			handler(val) {
				/* 表单数据初始化完成之后,如果内容变动，向外触发事件 */
                this.$emit("change", val);
                if(val){//向外暴露完整数据
                    this.$emit("change-detail", {
                      ...val,
                      ...this.api_result()
                    });
                }
			}
		}
	},
	created() {
		this.setOptions();
	},
    computed:{
        subjectProp(){//科目表单项动态绑定的属性 subjectProp是随便写的，为了保证内容为空显示出placeholder
            return this.disableObj.disableSubject?'subjectProp':'subjectId';
        }
    },
	data() {
		return {
			ownerList: [], // 研发人列表
			questionType: nlapp.Dictionary.get("rc_questionType"), //题型数据源
			basicForm: {
				//表单数据
				projectId: [],
				projectName: '',
				subjectId: "",
                subjectName:'',
				chapterIds: [],
                chapterList:[],//章节详细信息
				questionType: "",
				questionDeveloperId: "",
				questionDeveloperName: "",
                knowledgeList:[],//知识点
                knowledgeName:''//知识点名称
			},
			formOptions: {
				rules: {}
			},
			isValidate: false,
			rules: {
				projectId: [
					{
						required: true,
						message: "请选择项目",
						trigger: "change"
					}
				],
				subjectId: [
					{
						required: true,
						message: "请选择科目",
						trigger: "change"
					}
				]
			},
			knowledgeDialogData: {
				isShowKnowledgeDialog: false, // 是否展示知识点弹窗
				projectName: "",
				subjectId: "",
				subjectName: "",
                defaultData:[]
			}, // 知识点弹窗所需要的一些参数
            isShowKnowledgeDeleteDialog:false,//是否显示查询知识点弹窗
            //用于处理表单项被禁用回显逻辑
            disableObj:{
                disableProject:false,//项目是否不在列表中
                disableSubject:false,//科目是否不在列表中
                projectReady:false,//项目列表第一次初始化完成
                subjectReady:false,//科目列表第一次初始化完成
            }
		};
	},
	methods: {
        /**
		 * 判断之前选择的项目，是否不再列表中
		 * @param {Array} projectList 扁平化的项目列表
		 * @param {object} item 表单信息
		 */
		projectReady(projectList, item) {
            //列表第一次初始化完成
            if(!this.disableObj.projectReady){
                this.disableObj.projectReady = true;
                if (item.projectId.length && !projectList.some((i) => i.projectId === item.projectId[item.projectId.length - 1])) {
                    this.disableObj.disableProject = true;
                }
            }
            if(!this.disableObj.disableProject && item.projectId.length){
                const projectIdStr = item.projectId[item.projectId.length - 1];
                if(!this.disableObj.disableProject && projectIdStr){
                    this.basicForm.projectName = projectList.find((i) => i.projectId === projectIdStr).projectName;
                }
            }
		},
         /**
		 * 当科目不存在于科目列表时，
		 * @param {Array} subjectList 科目列表
		 * @param {object} item 表单信息
		 */
        subjectReady(subjectList,item){
            //列表第一次初始化完成 判断
            if(!this.disableObj.subjectReady){
                this.disableObj.subjectReady = true;
                if(item.subjectId && (!subjectList ||subjectList.length===0) ){
                    this.disableObj.disableSubject= true;
                    return;
                }
                if (item.subjectId && !subjectList.some((i) => i.subjectId === item.subjectId)) {
                    this.disableObj.disableSubject = true;
                }
            }
            if(!this.disableObj.disableSubject && item.subjectId){
                this.basicForm.subjectName = subjectList.find((i) => i.subjectId === item.subjectId).subjectName;
            }
        },
        developerReady(developerList,item){
            if(item.questionDeveloperId){
                const user= developerList.find((i) => i.teacherId === item.questionDeveloperId);
                this.basicForm.questionDeveloperName= `${user.userName}`;
            } else {
                this.basicForm.questionDeveloperName = '';
            }
        },
		/**
		 * 设置表单相关配置
		 * @param
		 * @param rules
		 */
		setOptions() {
			let opt = this.rulesPropList;
			let rules = {};
			if (rules && opt.length) {
				opt.forEach((ruleKey) => {
					rules[ruleKey] = this.rules[ruleKey];
				});
			}
			this.formOptions = {
				rules
			};
		},
		/**
		 * 切换项目
		 */
		onProjectChange(val) {
            this.basicForm = {
                ...this.basicForm,
                subjectId:"",
                subjectName:"",
            };
            if(this.disableObj.disableProject){
                this.disableObj.disableProject = false;
            }
            if(val && val.length){
                const projectIdStr = val[val.length - 1];
                this.basicForm.projectName = this.$refs.projectCascader.api_getCheckedNodes().find((i) => i.value === projectIdStr).label;
            }

            this.onSubjectChange();
		},
		/**
		 * 切换科目
		 */
		onSubjectChange(subjectId) {
            if(this.disableObj.disableSubject){
                this.disableObj.disableSubject = false;
                this.basicForm.subjectId = subjectId||'';
            }
            this.basicForm = {
                ...this.basicForm,
                chapterIds:[],
                chapterList:[],
                knowledgeName:'',
                knowledgeList:[]
            };
            if(subjectId){
                this.basicForm.subjectName = this.$refs.subjectSelect.api_getOptions().find((i) => i.subjectId === subjectId).subjectName;
            }
		},
        //切换研发人
        onDeveloperChange(questionDeveloperId){
            if(questionDeveloperId){
                let user = this.$refs.selectTeacher.api_getOptions().find((i) => i.teacherId === questionDeveloperId);
                this.basicForm.questionDeveloperName = user?`${user.userName}`:'';
            }else {
                this.basicForm.questionDeveloperName = '';
            }
        },
        // 章节信息变化
        onChapterChange(chapterList) {
			console.warn('onChapterChange', chapterList);
            this.basicForm.chapterList = chapterList;
        },
		/**
		 * 控制表单项是否展示
		 */
		isShow(key) {
			const isInclude = this.propList.includes(key);
			const isHidden = this.propList.findIndex((prop) => prop === key) + 1 <= this.max;
			return isInclude && isHidden;
		},
		/**
		 * 知识点弹窗聚焦
		 */
		onClickKnowledgePoint() {
			const {subjectId,projectName,subjectName } = this.basicForm;
			if (!subjectId) {
				this.$message.warning("请先选择项目和科目");
				return;
			}
			this.knowledgeDialogData = {
				isShowKnowledgeDialog: true,
				projectName,
				subjectId,
				subjectName,
                defaultData: this.basicForm.knowledgeList
			};
		},
        //知识点详情弹窗
        onShowKnowledgeDeleteDialog(){
            this.isShowKnowledgeDeleteDialog = true;
        },
        /**
         * 选择确定知识点弹窗
         * @param {*} knowledgeList
         */
        onKnowledgeSubmit(knowledgeList) {
            if(!knowledgeList.length){
                this.$message.warning("请选择知识点");
				return;
            }
            this.basicForm.knowledgeList = knowledgeList;
            if(!this.knowledgeMultiple) {
                this.basicForm.knowledgeName = knowledgeList[0].knowledgeName;
            }
            this.knowledgeDialogData.isShowKnowledgeDialog = false;
        },
        // 知识点单选-知识点框内X
        onDeleteKnowledge() {
            this.basicForm.knowledgeName = '';
            this.basicForm.knowledgeList=[];
        },
		/**
		 * 重置属性
		 */
		resetFiled() {
			this.$refs.basicForm.resetFields();
			this.basicForm = {
				//表单数据
				projectId: [],
				projectName: '',
				subjectId: "",
                subjectName:'',
				chapterIds: [],
                chapterList:[],//章节详细信息
				questionType: "",
				questionDeveloperId: "",
				questionDeveloperName: "",
                knowledgeList:[],//知识点
                knowledgeName:''//知识点名称
			};
		},
		/**
		 * 向外暴露,用于返回表单信息
		 * 项目和章节为级联选择返回的数组形式
		 */
		api_result() {
            const {
                projectId,
				subjectId,
                chapterIds,
                chapterList,
				questionType,
				questionDeveloperId,
                questionDeveloperName,
                knowledgeList,//知识点
                knowledgeName,
                projectName,
                subjectName
             } = this.basicForm;
			if (chapterList && this.$refs.chapterCascader) {
				const nodes = this.$refs.chapterCascader.api_getCheckedNodes();
				chapterList.forEach((item) => {
					const n = nodes.find(({ value }) => value === item.chapterId);
					this.$set(item, 'chapterFullId', n ? n.pathNodes.map(({ value }) => value).join('-') : '');
					this.$set(item, 'chapterFullName', n ? n.pathLabels.join('-') : '');
				});
			}
            let result = {
                projectId,
                projectName,
				subjectId,
				subjectName
            };
            if(this.propList.includes('chapter')){
                result.chapterList = chapterList;
                result.chapterIds = chapterIds;
            }
            if(this.propList.includes('knowledgePoint')){
                result.knowledgeList = knowledgeList;
                result.knowledgeName = knowledgeName;
            }
            if(this.propList.includes('questionType')){
                result.questionType = questionType;
            }
            if(this.propList.includes('questionDeveloperId')){
                result.questionDeveloperId = questionDeveloperId;
                result.questionDeveloperName = questionDeveloperId ? questionDeveloperName : '';
            }
			return result;
		},
		/**
		 * 向外暴露,重置数据
		 */
		api_reset() {
			this.resetFiled();
		},
		/**
		 * 向外暴露,校验表单项
		 */
		api_validateField() {
            return this.$refs.basicForm.validate().then((data)=>{
                return data;
            }).catch(data=>{
                return data;
            });
		}
	}
};
